package com.yyt2025;

import com.github.markusbernhardt.proxy.util.Logger;
import com.intellij.core.CoreBundle;
import com.intellij.lang.Language;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.*;
import com.yyt2025.util.StringSplitter;
import org.jetbrains.annotations.NotNull;
import org.jsoup.internal.StringUtil;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.ibm.icu.lang.UCharacter.GraphemeClusterBreak.T;

public class CodeGeneratorAction extends AnAction {

    @Override
    public void actionPerformed(@NotNull AnActionEvent e) {
        Project project = e.getProject();
        if (project == null) {
            return;
        }
        VirtualFile virtualFile = e.getData(PlatformDataKeys.VIRTUAL_FILE); // 获取当前文件所在目录

        PsiFile psiFile = e.getData(PlatformDataKeys.PSI_FILE); // 获取当前文件所在目录
        if (psiFile == null) {
            return;
        }

        // java 文件名
        String fileName = psiFile.getName();

        String entityName = getEntityName(fileName);
        Map<String, String> templateParams = new HashMap<>();
        templateParams.put("packageName", fileName);
        templateParams.put("entityName", entityName);
        templateParams.put("controllerName", entityName + "Controller");
        templateParams.put("serviceName", entityName + "Service");
        templateParams.put("serviceImplName", entityName + "ServiceImpl");
        templateParams.put("mapperName", entityName + "Mapper");
        templateParams.put("serviceInstance", entityName.toLowerCase() + "Service");
        templateParams.put("mapperInstance", entityName.toLowerCase() + "Mapper");

        generateFileFromTemplates(project,psiFile.getContainingDirectory(), EntityFileSuffixList, templateParams);

    }

    private String[] EntityFileSuffixList = {"Controller", "Service", "ServiceImpl","Mapper"};

    private void generateFileFromTemplates(Project project, PsiDirectory directory, String[] templateNames, Map<String, String> params) {
        for (String templatePrefix : templateNames){
            generateFileFromTemplate(project, directory, templatePrefix , params);
        }
    }
    private void generateFileFromTemplate(final Project project, final PsiDirectory directory, final String templatePrefix, Map<String, String> params){
        String templateName = templatePrefix + "Template.java";
        try {
            InputStream inputStream = getClass().getResourceAsStream("/templates/" + templateName);
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder templateContent = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    line = line.replace("$" + entry.getKey(), entry.getValue());
                }
                templateContent.append(line).append("\n");
            }
            reader.close();

            String fileName = params.get("entityName") + templateName.replace("Template", "");
            // 构建文件路径
            String filePath = directory.getParent() + File.separator + StringSplitter.splitByUpperCaseAndToLowerRelativePath(templatePrefix) + fileName;


            // 文件对象，创建新的 PsiFile
            PsiFileFactory psiFileFactory = PsiFileFactory.getInstance(project);
            Language language = Language.findLanguageByID("JAVA");
            PsiFile file = psiFileFactory.createFileFromText(fileName, language, templateContent.toString());

            if (null == (file.getContainingDirectory())) {

                ApplicationManager.getApplication().runWriteAction(() -> {

                    // 检查子目录是否存在
                    PsiDirectory subdirectory = null;
                    String[] directoryList = StringSplitter.splitByUpperCaseAndToLower(templatePrefix);
                    if (directoryList != null && directoryList.length > 0) {
                        subdirectory = directory.getParent();
                        for (int i = 0; i < directoryList.length; i++) {
                            PsiDirectory subdirectory_curr = subdirectory.findSubdirectory(directoryList[i]);
                            // 存在子目录，将 PsiFile 添加到子目录中
                            if (subdirectory_curr == null) {
                                // 子目录不存在，创建新的子目录
                                subdirectory = subdirectory.createSubdirectory(directoryList[i]);
                            } else {
                                subdirectory = subdirectory_curr;
                            }
                        }
                    }
                    if (subdirectory != null) {
                        // 将 PsiFile 添加到项目中
                        // 检查文件是否存在
                        PsiFile targetPsiFile = subdirectory.findFile(file.getName());
                        System.err.println("targetPsiFile:" + targetPsiFile);
                        System.err.println("subdirectory:" + subdirectory);

                        // 文件已存在
                        if (targetPsiFile == null) {
                            PsiElement newFile = subdirectory.add(file);
                        }
                    }
                });

            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private String getEntityName(String fileName) {
        if (StringUtil.isBlank(fileName)) {
            return null;
        }
        String entityName = fileName.substring(0, fileName.lastIndexOf("."));
        for (String suffix : EntityFileSuffixList){
            if (entityName.contains(suffix)) {
                entityName = entityName.substring(0, entityName.lastIndexOf(suffix) );
                return entityName;
            }
        }
        return entityName;
    }

}